/**
 * @filename:WishController 2021年9月14日
 * @project WishStar  V1.0
 * Copyright(c) 2020 huang Co. Ltd.
 * All right reserved.
 */
package com.huang.wishstar.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.huang.wishstar.entity.RequestData.CreateWish;
import com.huang.wishstar.entity.RequestData.DelayWish;
import com.huang.wishstar.entity.RequestData.UpdateWish;
import com.huang.wishstar.entity.Users;
import com.huang.wishstar.entity.Wish;
import com.huang.wishstar.entity.vo.GetWishVO;
import com.huang.wishstar.service.UsersService;
import com.huang.wishstar.service.WishService;
import com.huang.wishstar.utils.ApiResponse;
import com.huang.wishstar.utils.Converter;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import io.swagger.annotations.Api;

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>自动生成工具：mybatis-dsc-generator</p>
 *
 * <p>说明： 愿望表API接口层</P>
 * @version: V1.0
 * @author: huang
 * @time    2021年9月14日
 *
 */
@Api(tags = "愿望管理" ,description = "WishController")
@RestController
@RequestMapping("/wish")
public class WishController {
    @Autowired
    WishService wishService;
    @Autowired
    private UsersService usersService;

    @ApiOperation(value = "首页/创建一个新的愿望记录", notes = "愿望预期完成日期wishDate类型为LocalDate,前端可用这行代码完成:LocalDate wishDate = LocalDate.of(2021,9,26)，年月日是前端通过选择器选择的且愿望日期必须大于今天日期。由于AS也是java，所以本次项目开发前后端统一用LocalDate比较简单。如果是和vue或者其他前端可能long时间戳比较好")
    @PostMapping("/create")
    public ApiResponse<String> create(@ApiParam(value="愿望信息",required = true) @RequestBody(required=true) CreateWish requestData) throws JsonProcessingException {
        Wish wishEntity = new Wish();
        wishEntity.setUserId(requestData.getUserId());
        wishEntity.setWishTitle(requestData.getWishTitle());
        wishEntity.setWishDate(requestData.getWishDate());
        wishEntity.setWishIcon(requestData.getWishIcon());
        wishEntity.setWishDetails(null);
        wishEntity.setFavourNum(0);
        wishEntity.setIsFinish(0);
        wishEntity.setFinishTime(null);
        Boolean flag = wishService.save(wishEntity);
        if(flag==true){
            return ApiResponse.<String>builder().code(200).message("新建成功").data(null).build();}
        else{
            return ApiResponse.<String>builder().code(400).message("新建失败").data(null).build();
        }
    }

    @ApiOperation(value = "首页/根据wishId删除一个愿望", notes = "")
    //注意是@PathVariable 不是@PathParam ；这个是路径传值
    @DeleteMapping("/delete/{wishId}")
    public ApiResponse<String> DeleteWishById(@ApiParam(value="愿望id",required = true) @PathVariable("wishId") Integer wishId){
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("wish_id",wishId);
        Boolean b = wishService.remove(wrapper);
        if (b == true){
            return ApiResponse.<String>builder().code(200).message("删除成功").data(b.toString()).build();
        }
        else {
            return ApiResponse.<String>builder().code(400).message("删除失败").data(b.toString()).build();
        }
    }

    @ApiOperation(value = "首页/愿望完成时打卡", notes = "")
    @PutMapping("/finishWish")
    public ApiResponse<String> finishWish(@ApiParam(value="",required = true) @RequestBody(required=true) UpdateWish requestData) throws JsonProcessingException {

        Wish wishEntity = new Wish();

//        //先判断该id对应的习惯是不是已经被删或归档了，因为只有坚持中才能打卡
        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("wish_id",requestData.getWishId());
        int isUserExist = wishService.count(wrapper);
        if(isUserExist == 0){return ApiResponse.<String>builder().code(400).message("该愿望id对应的愿望不存在，无法完成打卡").data(null).build();}
//        //完成后更新details和日期
        wishEntity.setWishDetails(requestData.getWishDetails());
        wishEntity.setIsFinish(1);
        wishEntity.setFinishTime(LocalDate.now());
        Boolean flag = wishService.update(wishEntity,wrapper);
        if(flag==true){
            return ApiResponse.<String>builder().code(200).message("愿望打卡成功").data(null).build();}
        else{
            return ApiResponse.<String>builder().code(400).message("愿望打卡失败").data(null).build();
        }

    }

    @ApiOperation(value = "首页/查找某用户的未完成的所有愿望（已被合并）", notes = "注意:该接口已经合并入/habit/getMyhabitAndWish/{userId}，所以不要继续使用该接口。conutdownDays表示距离愿望预期完成时间还有几天。传入的wishDate是LocalDate类型，后端经过处理后数据库保存为YYYY-MM-DD的形式。查询出来的是不仅是未完成，且还没到到预期日期。sql查询条件为userId和is_finish=0。")
    @GetMapping("/getMyWish/{userId}")
    @ResponseBody
    public ApiResponse<List<GetWishVO>> getMyWish(@ApiParam(value="用户id",required = true) @PathVariable(value="userId",required=true) Integer userId) {
        //先判断用户是否存在
        QueryWrapper<Users> wrapper1 = new QueryWrapper<>();
        wrapper1.eq("user_id",userId).last("limit 1");
        int isUserExist = usersService.count(wrapper1);
        if(isUserExist == 0){
            return ApiResponse.<List<GetWishVO>>builder().code(400).message("用户id有误").data(null).build();
        }
        //查询条件：用户id、is_finish和愿望日期是否在未来，来选取该用户未完成的所有愿望
        QueryWrapper<Wish> wrapperWish = new QueryWrapper<>();
        wrapperWish.eq("user_id",userId);//要和数据库的一样，带下划线的不能转大写
        wrapperWish.eq("is_finish",0);
        wrapperWish.gt("wish_date",LocalDate.now());//只选取wishdate还在未来的记录
        List<Wish> wishEntities = wishService.list(wrapperWish);
        List<GetWishVO> wishVOList = new ArrayList<>();
        //获取愿望需要计算到预期达成愿望还有多少天，需要和今天的日期作比较
        for(int i=0;i<wishEntities.size();i++){
            //利用工具类计算今天到预期的相差时间,主要是要新增一个倒计时天数的字段，其实这个实体转vo应该自定义方法写在service里面
            GetWishVO wishVO = new GetWishVO();//将wish实体类转化为vo
            LocalDate wishDate = wishEntities.get(i).getWishDate();
            long ConutdownDays= LocalDate.now().until(wishDate, ChronoUnit.DAYS);
            wishVO.setConutdownDays(Converter.getAsInteger(ConutdownDays));
            System.out.println("距预期愿望完成还有多少天："+ConutdownDays);
            wishVO.setWishIcon(wishEntities.get(i).getWishIcon());
            wishVO.setWishTitle(wishEntities.get(i).getWishTitle());
            wishVO.setWishId(wishEntities.get(i).getWishId());
            wishVOList.add(wishVO);
        }
        if(wishVOList.size() !=0){
            return ApiResponse.<List<GetWishVO>>builder().code(200).message("获取成功").data(wishVOList).build();
        }else{
            return ApiResponse.<List<GetWishVO>>builder().code(400).message("获取失败").data(null).build();
        }

    }

    @ApiOperation(value = "愿望星页/查找所有用户的已经完成的愿望(愿望星)", notes = "")
    @GetMapping("/getAllFinishedWish")
    @ResponseBody
    public ApiResponse<List<Wish>> getAllFinishedWish() {
        //愿望池查询条件最简单，只需要已完成的愿望都返回，因为该接口功能是展示所有已完成的愿望
        QueryWrapper<Wish> wrapper = new QueryWrapper<>();
        wrapper.eq("is_finish",1);
        List<Wish> wishEntities = wishService.list(wrapper);
        if(wishEntities.size() !=0){
            return ApiResponse.<List<Wish>>builder().code(200).message("获取成功").data(wishEntities).build();
        }else{
            return ApiResponse.<List<Wish>>builder().code(400).message("获取失败").data(null).build();
        }

    }

    @ApiOperation(value = "愿望星页/给愿望星里的一个愿望点赞", notes = "")
    @PutMapping("/likeOneWish/{wishId}")
    public ApiResponse<String> likeOneWish(@ApiParam(value="愿望id",required = true) @PathVariable(value="wishId",required=true) Integer wishId) throws JsonProcessingException {


        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("wish_id",wishId);
        Wish wishEntity = wishService.getOne(wrapper);
        if(wishEntity == null){return ApiResponse.<String>builder().code(400).message("该愿望id对应的愿望不存在，无法点赞").data(null).build();}
        wishEntity.setFavourNum(wishEntity.getFavourNum()+1);
        Boolean flag = wishService.update(wishEntity,wrapper);
        if(flag==true){
            return ApiResponse.<String>builder().code(200).message("愿望点赞成功").data(null).build();}
        else{
            return ApiResponse.<String>builder().code(400).message("愿望点赞失败").data(null).build();
        }

    }


    @ApiOperation(value = "首页/愿望延期", notes = "接口说明：因为创建愿望时会设置一个预期达成日期，到如果到这一天，用户还没有点完成，那么app将会提醒用户今天是最后一天了请完成或者延期。newWishDate类型为LocalDate,前端可用这行代码完成:LocalDate newWishDate = LocalDate.of(2021,9,26)，年月日是前端用户自己选择的。")
    @PutMapping("/delay")
    public ApiResponse<String> delay(@ApiParam(value="愿望延期需传入wishId和newWishDate",required = true) @RequestBody(required=true) DelayWish requestData)  {

        QueryWrapper wrapper = new QueryWrapper();
        wrapper.eq("wish_id",requestData.getWishId());
        Wish wishEntity = wishService.getOne(wrapper);
        if(wishEntity == null){return ApiResponse.<String>builder().code(400).message("该愿望id对应的愿望不存在，无法延期").data(null).build();}
        wishEntity.setWishDate(requestData.getNewWishDate());
        Boolean flag = wishService.update(wishEntity,wrapper);
        if(flag==true){
            return ApiResponse.<String>builder().code(200).message("愿望延期成功").data(null).build();}
        else{
            return ApiResponse.<String>builder().code(400).message("愿望延期失败").data(null).build();

        }
    }


}